import dayjs from "dayjs";

class Util {
  // 防抖函数
  public debounce(fn: Function, delay: number) {
    return () => {
      let timer = null;
      if (timer) clearInterval(timer);
      timer = setTimeout(() => {
        fn.call(this, arguments);
      }, delay);
    };
  }

  //节流函数
  public throttle(fn: Function, delay: number) {
    let timer: any = null;
    return () => {
      if (timer) return;
      timer = setTimeout(() => {
        fn.call(this, arguments);
        timer = null;
      }, delay);
    };
  }

  //自动填充年龄
  public fillAge(bir: string) {
    // const bir = JSON.stringify(birday)

    const year = bir.substring(1, 5);
    const month = bir.substring(6, 8);
    const day = bir.substring(9, 11);

    const date = new Date();
    const monthNow = date.getMonth() + 1;
    const dayNow = date.getDay();
    const yearNow = date.getFullYear();
    const age = yearNow - Number(year);
    if (
      Number(month) > monthNow ||
      (monthNow == Number(month) && dayNow < Number(day))
    ) {
      return age - 1;
    }
    return age;
  }

  //时分秒
  public day(time?: string) {
    return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
  }
  //年月日
  public ymd(time: string) {
    return dayjs(time).format("YYYY-MM-DD");
  }
}

const utils = new Util();
export default utils;
